# Setup Java 21 LTS
Write-Host "Setting up Java 21 LTS..." -ForegroundColor Green

# Download Java 21
$url = "https://download.java.net/java/GA/jdk21.0.2/f2283984656d49d69e91c558476027ac/13/GPL/openjdk-21.0.2_windows-x64_bin.zip"
$zip = "$env:TEMP\openjdk-21.zip"
$installPath = "C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot"

Write-Host "Downloading Java 21..." -ForegroundColor Yellow
Invoke-WebRequest -Uri $url -OutFile $zip -UseBasicParsing

Write-Host "Installing Java 21..." -ForegroundColor Yellow
if (!(Test-Path $installPath)) {
    New-Item -ItemType Directory -Path $installPath -Force
}

Expand-Archive -Path $zip -DestinationPath "C:\Program Files\Eclipse Adoptium\" -Force

# Find and rename extracted folder
$extracted = Get-ChildItem "C:\Program Files\Eclipse Adoptium\" | Where-Object { $_.Name -like "jdk-21*" -and $_.Name -notlike "*hotspot" } | Select-Object -First 1
if ($extracted) {
    if (Test-Path $installPath) {
        Remove-Item $installPath -Recurse -Force
    }
    Rename-Item $extracted.FullName $installPath -Force
}

# Set environment variables
Write-Host "Setting environment variables..." -ForegroundColor Yellow
[Environment]::SetEnvironmentVariable("JAVA_HOME", $installPath, "User")

$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
$javaBin = "$installPath\bin"
$pathArray = $currentPath -split ";" | Where-Object { $_ -notlike "*jdk*\bin" -and $_ -notlike "*java*\bin" }
$newPath = ($javaBin, $pathArray) -join ";"
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")

# Refresh current session
$env:JAVA_HOME = $installPath
$env:Path = "$javaBin;$env:Path"

Write-Host "JAVA_HOME: $installPath" -ForegroundColor Cyan

# Verify installation
Write-Host "Verifying installation..." -ForegroundColor Yellow
& "$javaBin\java.exe" -version

# Cleanup
Remove-Item $zip -Force

Write-Host "Java 21 setup complete! Please restart PowerShell or IDE." -ForegroundColor Green